<?php
/**
 * 自动生成订单
 */

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/lib_goods.php');
require_once(ROOT_PATH . 'includes/lib_clips.php');
require_once(ROOT_PATH . 'includes/lib_payment.php');
@ini_set('display_errors',       1);
$act = !empty($_REQUEST['act'])?$_REQUEST['act']:'default';

/*默认页面*/
if ($act == 'default' ) {
    /* 检查权限 */
    admin_priv('order_virtual');

    $smarty->assign('ur_here',         "添加虚拟订单");
    $smarty->display("virtual/virtual.htm");
}
/*处理提交数据*/
if ($act =='post') {
    /* 检查权限 */
    admin_priv('order_virtual');

    $money = !empty($_REQUEST['money'])?$_REQUEST['money']:'100';
    $goodsMoney = 0;
    /*获取随机商品*/
    while ($goodsMoney <= $money) {
    $sql =  " SELECT goods_id,goods_name,goods_sku,market_price,shop_price AS goods_price FROM ".$ecs->table('goods').
            " WHERE goods_id >= (SELECT floor(RAND() * (SELECT MAX(goods_id) FROM ".$ecs->table('goods')."))) AND shop_price <= '$money'".
            " ORDER BY goods_id LIMIT 1";
    $goods = $db->getRow($sql);
    $goodsList[]=$goods;
    $goodsMoney +=$goods['goods_price'];
    }
    /*获取用户地址信息*/
    $sql = "SELECT * FROM ".$ecs->table('user_address')." ORDER BY RAND() LIMIT 1";
    $consignee=$db->getRow($sql);
    /*初始订单基本信息*/
    $order = array(
        'shipping_id'     => 13,
        'shipping_name'   => '速递',
        'pay_id'          => '1',
        'pay_name'        => '支付宝',
        'postscript'      => '',
        'user_id'         => 3,
        'add_time'        => time(),
        'order_status'    => 0,
        'shipping_status' => 0,
        'pay_status'      => 0,
        'country'         => 1,
        'province'        => $consignee['province'],
        'city'            => $consignee['city'],
        'district'        => $consignee['district'],
        'area_id'         => 3,
        'consignee'       => $consignee['consignee'],
        'address'         => $consignee['address'],
        'mobile'          => $consignee['mobile'],
        'agency_id'       => 3,
        'goods_amount'    => $goodsMoney,
        'shipping_fee'    => '0',
        'from_ad'         => '7',
        'referer'         => '虚拟订单',
        'order_amount'    => $goodsMoney,
        'wcShippingId'    => 1,
        'invoice_no'      => rand(123456789012, 987654321098)
        );
    $order['order_sn'] = get_order_sn(); //获取新订单号
    $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT', '', 'SILENT');
    $new_order_id = $GLOBALS['db']->insert_id(); // 获取新插入的订单ID
    $order['log_id'] = insert_pay_log($new_order_id, $order['order_amount'], PAY_ORDER);

    $sql =  " INSERT INTO ".$ecs->table('order_goods')."( order_id,goods_id,goods_name, goods_sku, goods_number, market_price,goods_price,is_real, user_name, add_time) VALUES ";
    foreach ($goodsList as $key => $g) {
        $sqlArr[] = "($new_order_id,'$g[goods_id]','$g[goods_name]','$g[goods_sku]','1','$g[market_price]','$g[goods_price]','1','" . getRandUsers() . "','".time()."')";
    }
    $sql .= implode(',', $sqlArr);
    $db->query($sql);
    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'virtual.php?act=default', 'text' => '订单已生成，可到列表进行付款操作');
    sys_msg('订单已成功生成', 0, $link);
}

if ($act =='list') {

    /* 检查权限 */
    admin_priv('order_virtual');

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['02_order_list']);
    $smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => $_LANG['03_order_query']));

    $smarty->assign('status_list', $_LANG['cs']);   // 订单状态
    $smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
    $smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
    $smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
    $smarty->assign('full_page',        1);
    $order_list = order_list();
    if (!empty($_POST['downData']) && !empty($order_list['orders'])) {
        include_once('includes/cls_phpzip.php');
        $zip = new PHPZip;
        $content = '';
        echo "订单号,下单时间,总额,商户订单号\n";
        foreach ($order_list['orders'] as $key => $value) {
            $v = array();
            $v['order_sn'] = 'sn_'.$value['order_sn'];
            $v['order_time'] = $value['order_time'];
            $v['total_fee'] = $value['total_fee'];
            $v['out_trade_no'] = 'no_' . $value['out_trade_no'];
            echo implode(",", $v) . "\n";
        }
        header("Content-type: application/vnd.ms-excel; charset=utf-8");
        Header("Content-Disposition: attachment; filename=order_list.csv");
        exit;
    }
    $smarty->assign('time_start',    date("Y-m-d",(time()-86400*30)));
    $smarty->assign('time_end',    date("Y-m-d",time()+86400));
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $smarty->display('virtual/virtual_list.htm');
}

if ($act == 'query') {
    /* 检查权限 */
    admin_priv('order_virtual');
    $order_list = order_list();
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    make_json_result($smarty->fetch('virtual/virtual_list.htm'), '', array('filter' => $order_list['filter'], 'page_count' => $order_list['page_count']));
}



/**
 *  获取订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list($user_id = '3')
{
    /* 分页大小 */
    $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

    if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
    {
        $filter['page_size'] = intval($_REQUEST['page_size']);
    }
    elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
    {
        $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
    }
    else
    {
        $filter['page_size'] = 15;
    }

    if (!empty($_POST['downData'])) {
        $filter['page'] = 1;
        $filter['page_size'] = 10000000;
    }

    $where = " o.user_id = $user_id";

    /* 查询条件 */
    if (!empty($_REQUEST['order_sn']) && intval($_REQUEST['order_sn'])) {
        $where .= " AND o.order_sn = {$_REQUEST['order_sn']}";
    }
    if (!empty($_REQUEST['status']) && intval($_REQUEST['status'])) {

    }
    if (!empty($_REQUEST['start_time']) && $start_time = strtotime(trim($_REQUEST['start_time']))) {
        $where .= " AND o.add_time > $start_time";
        $GLOBALS['smarty']->assign('time_start', $_REQUEST['start_time']);
    }
    if (!empty($_REQUEST['end_time']) && $end_time = strtotime(trim($_REQUEST['end_time']))) {
        $where .= " AND o.add_time < $end_time";
        $GLOBALS['smarty']->assign('time_end', $_REQUEST['end_time']);
    }

    /* 记录总数 */
    $sql = "SELECT COUNT(*) FROM egg_order_info AS o WHERE $where";

    $filter['record_count']   = $GLOBALS['db']->getOne($sql);
    $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

    /* 查询 */
    $sql = "SELECT o.order_id,o.order_sn, o.add_time, o.order_status, o.shipping_status, o.order_amount, o.money_paid, o.province, o.city, o.district, o.shipping_fee, o.pay_name,o.wangcangstatus, o.goods_amount,
        o.pay_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, o.pay_id ,
        u.user_name, u.user_id
        FROM egg_order_info o LEFT JOIN egg_users u ON u.user_id = o.user_id WHERE $where
        ORDER BY o.order_id DESC
        LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

    $orderList = $GLOBALS['db']->getAll($sql);
    foreach ($orderList as $key => $value) {
        //支付方式信息
        $payment_info = array();
        $payment_info = payment_info($value['pay_id']);

        //无效支付方式
        if ($payment_info === false)
        {
            $value['pay_online'] = '';
        }
        else
        {
            //取得支付信息，生成支付代码
            $payment = unserialize_config($payment_info['pay_config']);
            /* 调用相应的支付方式文件 */
            include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php');
            //获取需要支付的log_id
            $value['log_id']    = get_paylog_id($value['order_id'], $pay_type = PAY_ORDER);
            $value['pay_desc']  = $payment_info['pay_desc'];
            /* 取得在线支付方式的支付按钮 */
            $pay_obj    = new $payment_info['pay_code'];
            $value['pay_online'] = $pay_obj->get_code($value, $payment, true);
        }
        $value['total_fee'] = $value['goods_amount']+$value['shipping_fee'];
        $value['order_time'] = date('Y-m-d H:i:s', $value['add_time']);
        $value['out_trade_no'] = $value['order_sn'].$value['log_id'];
        $orderList[$key] = $value;
    }

    $arr = array('orders' => $orderList, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    return $arr;
}

/**
 * 随机获取用户名
 * @return str   用户名
 */
function getRandUsers() {
    $sql = "SELECT user_name FROM egg_users ORDER BY RAND() LIMIT 2";
    $arr = $GLOBALS['db']->getCol($sql);
    $str = substr($arr[0],3) . substr($arr[1],-3);
    return $str;
}